import axios, { type Method } from 'axios'
import { getLocalToken } from './auth'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'

const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000,
})

/**
 * 请求拦截器
 */
service.interceptors.request.use(
  config => {
    const token  = getLocalToken()
    if(token){
       config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => { 
    // 处理token失效
    if(error.response.status === 401){
      ElMessage.error('token失效, 请重新登录');
      const store = useUserStore()
      store.setToken('')
      router.replace('/login')
    } else {
       ElMessage.error(error.response.data.msg);
    }
    return Promise.reject(error)
  },
)

type Data<T> = {
  code: number
  message: string
  data: T
}

/**
 * 封装一个request方法
 */
const request = <T>(url: string, method: Method = 'GET', submitObj?: object)=>{
  return service.request<T, Data<T>>({
    url,
    method,
    [ method.toLowerCase() === 'get' ? 'params' : 'data' ]: submitObj
  })
}

export { request, service }
